package com.hotline.monitor.service.agent;


import com.alibaba.fastjson.JSON;
import com.hotline.monitor.constant.Constants;
import com.hotline.monitor.dto.AgentResultDTO;
import com.hotline.monitor.dto.LoginDTO;
import com.hotline.monitor.enums.ReturnCodeEnum;
import com.hotline.monitor.util.HttpUtils;
import com.hotline.monitor.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;

@Service
@Slf4j
public class OnlineAgentServiceImpl implements OnlineAgentService {

    private static final String URI_LOGIN = "/agentgateway/resource/onlineagent/{}";

    private static final String URI_FORCE_LOGIN = "/agentgateway/resource/onlineagent/{}/forcelogin";

    private static final String URI_LOGOUT = "/agentgateway/resource/onlineagent/{}/logout";

    private static final String URI_AGENTEVENT = "/agentgateway/resource/agentevent/{}";

    @Value("${hotline.url}")
    private String url;

    @Value("${agent.worknumber}")
    private String workNumber;

    @Value("${agent.phonenum}")
    private String phoneNum;

    @Value("${agent.password}")
    private String password;

    @Value("${agent.agenttype:4}")
    private Integer agenttype;

    /**
     * 坐席签入
     *
     * @return
     */
    @Override
    public String login() {

        try {
            String reqUrl = url + URI_LOGIN;
            reqUrl = StringUtils.format(reqUrl, workNumber);

            String guid = login(reqUrl);
            if (StringUtils.isNotBlank(guid)) {
                log.info("坐席签入成功，GUID：{}", guid);
                return guid;
            }
            //签入失败，强制签入
            log.info("坐席签入失败，强制签入");
            String forceLoginUrl = url + URI_FORCE_LOGIN;
            forceLoginUrl = StringUtils.format(forceLoginUrl, workNumber);
            guid = login(forceLoginUrl);
            log.info("坐席强制签入成功，GUID：{}", guid);
            return guid;

        } catch (Exception e) {
            log.error("坐席登陆失败:{}", e.getMessage());
        }
        return StringUtils.EMPTY;
    }

    public void agentevent(){
        try {
            String reqUrl = url + URI_AGENTEVENT;
            reqUrl = StringUtils.format(reqUrl, workNumber);
            Map<String, String> header = new HashMap<>();
            header.put("Guid", Constants.HEADER_GUID);
            Map<String,String> result = HttpUtils.doGetMap(reqUrl,new HashMap<>(),header);
            String guid = result.get("guid");
            if(StringUtils.isNotBlank(guid)) {//替换guid
                Constants.HEADER_GUID = guid;
            }
            log.info("轮询方式获取单座席事件成功，result：{}", JSON.toJSONString(result));
        }catch (Exception e){
            log.error("轮询方式获取单座席事件失败:{}", e.getMessage());
        }
    }

    @Override
    public void logout() {
        String reqUrl = url + URI_LOGOUT;
        reqUrl = StringUtils.format(reqUrl, workNumber);

        Map<String, String> header = new HashMap<>();
        header.put("Guid", Constants.HEADER_GUID);
        String resultString = HttpUtils.doDeleteJson(reqUrl, header);

        log.info("坐席签出返回：{}", resultString);
    }

    /**
     * 坐席签入
     *
     * @param url
     * @return
     */
    private String login(String url) {
        try {
            LoginDTO loginDTO = new LoginDTO();
            loginDTO.setPhonenum(phoneNum);
            loginDTO.setPassword(password);
            loginDTO.setAgenttype(agenttype);

            Map<String, String> result = HttpUtils.doPutJson(url, JSON.toJSONString(loginDTO));
            String resultString = result.get("result");
            String guid = result.get("guid");
            log.info("坐席签入返回：{},坐席签入Header GUID：{}", resultString, guid);
            if (StringUtils.isNotBlank(resultString)) {
                AgentResultDTO agentResultDTO = JSON.parseObject(resultString, AgentResultDTO.class);
                //坐席签入成功
                if (ReturnCodeEnum.SUCCESS.getCode().equals(agentResultDTO.getRetcode()) && StringUtils.isNotBlank(guid)) {
                    guid = org.springframework.util.StringUtils.replace(guid, "JSESSIONID=", "");
                    return guid;
                }
            }
        } catch (Exception e) {
            log.error("坐席登陆失败:{}", e.getMessage());
        }
        return StringUtils.EMPTY;
    }

}
